package com.zhang.third.day03;

import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.source.SourceFunction;
import org.apache.flink.util.Collector;

import java.util.Random;

/**
 * @title: KeyedProcessFunction一次性求最大值、最小值、总和、总条数、平均值 实现限流
 * @author: zhang
 * @date: 2022/4/6 15:38
 */
public class Example11 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .addSource(new SourceFunction<Integer>() {
                    private boolean running = true;
                    private Random random = new Random();

                    @Override
                    public void run(SourceContext<Integer> ctx) throws Exception {
                        while (running) {
                            ctx.collect(random.nextInt(1000));
                            Thread.sleep(10L);
                        }
                    }

                    @Override
                    public void cancel() {
                        running = false;
                    }
                })
                .keyBy(r -> 1)
                .process(new KeyedProcessFunction<Integer, Integer, IntStatistics>() {
                    private ValueState<IntStatistics> acc;

                    private ValueState<Boolean> flag;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        acc = getRuntimeContext().getState(
                                new ValueStateDescriptor<IntStatistics>(
                                        "acc",
                                        Types.POJO(IntStatistics.class)
                                )
                        );

                        flag = getRuntimeContext().getState(
                                new ValueStateDescriptor<Boolean>(
                                        "flag", Types.BOOLEAN
                                )
                        );
                    }

                    @Override
                    public void processElement(Integer value, KeyedProcessFunction<Integer, Integer, IntStatistics>.Context ctx, Collector<IntStatistics> out) throws Exception {
                        if (acc.value() == null) {
                            acc.update(new IntStatistics(
                                    value,
                                    value,
                                    value,
                                    1,
                                    value
                            ));
                        } else {
                            IntStatistics tmp = acc.value();
                            acc.update(new IntStatistics(
                                    Math.min(value, tmp.min),
                                    Math.max(value, tmp.max),
                                    value + tmp.sum,
                                    tmp.count + 1,
                                    (value + tmp.sum) / (tmp.count + 1)
                            ));
                        }

                        if (flag.value() == null) {
                            long currTs = ctx.timerService().currentProcessingTime();
                            long tenSecLater = currTs + 10 * 1000L;
                            ctx.timerService().registerProcessingTimeTimer(tenSecLater);
                            flag.update(true);
                        }
                    }

                    @Override
                    public void onTimer(long timestamp, KeyedProcessFunction<Integer, Integer, IntStatistics>.OnTimerContext ctx, Collector<IntStatistics> out) throws Exception {
                        out.collect(acc.value());
                        flag.clear();
                    }
                })
                .print();


        env.execute();
    }

    public static class IntStatistics {
        public Integer min;
        public Integer max;
        public Integer sum;
        public Integer count;
        public Integer avg;

        public IntStatistics() {
        }

        public IntStatistics(Integer min, Integer max, Integer sum, Integer count, Integer avg) {
            this.min = min;
            this.max = max;
            this.sum = sum;
            this.count = count;
            this.avg = avg;
        }

        @Override
        public String toString() {
            return "IntStatistics{" +
                    "min=" + min +
                    ", max=" + max +
                    ", sum=" + sum +
                    ", count=" + count +
                    ", avg=" + avg +
                    '}';
        }
    }
}
